﻿package ua.mihaylenko.cardsplugin.tabBar 
{
	import fl.data.DataProvider;
	import flash.display.Sprite;
	public class TabBar extends Sprite
	{
		//private var tabData:Array = [ "Designs", "Stock images", "Embed" ]; 
		private var tabs:Array = [];
		private var _dataProvider:DataProvider;
		private var _selectedIndex:int = -1;
		public function TabBar()
		{
			//this.dataProvider = new DataProvider( tabData );
		}
		
		public function set dataProvider(value:DataProvider):void
		{
			_dataProvider = value;
			drawTabs();
		}
		
		public function set selectedIndex(value:int):void
		{
			if ( _selectedIndex == value) return;
			selectTab(_selectedIndex, false);
			_selectedIndex = value;
			if (_selectedIndex >= 0 && _selectedIndex < this.tabs.length)
			{
				selectTab(_selectedIndex, true);
				var item:Object = this._dataProvider.getItemAt(_selectedIndex);
				this.dispatchEvent(new TabEvent(TabEvent.TABCHANGE, false, false, _selectedIndex, item["label"]));
			}
		}
		
		public function get selectedIndex():int
		{
			return _selectedIndex;
		}
		
		private function selectTab(index:int, value:Boolean):void
		{
			if (index >= 0)
			{
				var button:TabButton = this.tabs[index] as TabButton;
				if(button) button.selected = value;
			}
		}
		
		protected function drawTabs():void
		{
			var buttonCount:int = this._dataProvider.length;
			var xPosition:Number = 0;
			removeTabs();
			for(var i:int = 0; i < buttonCount; i++)
			{
				var button:TabButton = new TabButton();
				button.addEventListener(TabEvent.TABSELECTED, buttonChangeHandler, false, 0, true);
				this.addChild(button);				
				this.tabs.push(button);				
				var item:Object = this._dataProvider.getItemAt(i);
				button.text = item["label"];
				if (i == buttonCount - 1) button.isLast = true;
				
				button.selected = this._selectedIndex == i;
				button.x = xPosition;
				xPosition += button.getWidth();
			}
		}
		
		private function removeTabs():void
		{
			for (var i:int = 0; i < this.tabs.length; i++)
			{
				var button:TabButton = this.tabs[i] as TabButton;
				button.removeEventListener(TabEvent.TABSELECTED, buttonChangeHandler);
				this.removeChild(button);
				button = null;
			}
			this.tabs = [];
		}
		
		private function buttonChangeHandler(event:TabEvent):void
		{
			var button:TabButton = event.currentTarget as TabButton;
			var index:int = this.tabs.indexOf(button);
			var item:Object = this._dataProvider.getItemAt(index);
			selectedIndex = index;
		}
	}
	
}